﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.Cache;
using YasharEl.Infrastructure.Caching.Orm;
using System.Diagnostics.Contracts;

namespace YasharEl.Infrastructure.Caching.NHibernate.Integration
{
    public class NHibernateOrmCacheAdapter : ICache
    {
        #region Fields

        private readonly IOrmCacheManager _ormCacheManager;
        private readonly string _regionName;

        #endregion

        #region Constructors

        public NHibernateOrmCacheAdapter(IOrmCacheManager ormCacheManager, string regionName)
        {
            Contract.Requires<ArgumentNullException>(ormCacheManager != null, "ormCacheManager could not be null.");
            Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(regionName), "regionName could not be null or empty.");

            _ormCacheManager = ormCacheManager;
            _regionName = regionName;
        }

        #endregion

        #region ICache Implementations

        /// <summary>
        /// Clear the cache.
        /// </summary>
        /// <exception cref="CacheException"></exception>
        public virtual void Clear()
        {
            _ormCacheManager.Flush();
        }

        /// <summary>
        /// Clean up.
        /// </summary>
        public virtual void Destroy()
        {
            _ormCacheManager.Destroy();
        }

        public virtual object Get(object key)
        {
            return _ormCacheManager.GetData(key.ToString());
        }

        public virtual void Lock(object key)
        {
            _ormCacheManager.Lock(key.ToString());
        }

        public virtual long NextTimestamp()
        {
            return Timestamper.Next();
        }

        public virtual void Put(object key, object value)
        {
            _ormCacheManager.Add(key.ToString(), value);
        }

        public virtual string RegionName
        {
            get { return _regionName; }
        }

        public virtual void Remove(object key)
        {
            _ormCacheManager.Remove(key.ToString());
        }

        public virtual int Timeout
        {
            get { return _ormCacheManager.LockTimeout; }
        }

        public virtual void Unlock(object key)
        {
            _ormCacheManager.Unlock(key.ToString());
        }

        #endregion
    }
}
